package org.veloxbot.api.methods;

import org.veloxbot.api.internals.concurrent.Task;

import org.veloxbot.ui.Chrome;

import java.awt.AWTKeyStroke;

import java.awt.event.KeyEvent;

/**
 * @author Static
 */
public class Keyboard {

	private static KeyEvent create(final int id, final int modifiers, final int code, final char c, final int location) {
		return new KeyEvent(Chrome.bot.displayPanel, id, System.currentTimeMillis(), modifiers, code, c, location);
	}

	/**
	 * Presses the enter key.
	 */
	public static void pressEnter() {
		pressEventKey(KeyEvent.VK_ENTER);
	}

	/**
	 * Presses the key of the given parameter.
	 *
	 * @param mouseEventKey A Constant variable within the KeyEvent class.
	 */
	public static void pressEventKey(final int mouseEventKey) {
		Chrome.bot.nazi.redispatch(create(KeyEvent.KEY_PRESSED, 0, mouseEventKey, (char) mouseEventKey, KeyEvent.KEY_LOCATION_STANDARD));
		Task.sleep(50, 75);
		Chrome.bot.nazi.redispatch(create(KeyEvent.KEY_RELEASED, 0, mouseEventKey, (char) mouseEventKey, KeyEvent.KEY_LOCATION_STANDARD));
	}

	/**
	 * Presses the key of the given parameter.
	 *
	 * @param c The character to press.
	 */
	public static void pressKey(final char c) {
		final AWTKeyStroke keystroke = AWTKeyStroke.getAWTKeyStroke(c);
		int keycode = keystroke.getKeyCode();
		if (c >= 'a' && c <= 'z') {
			keycode -= 32;
		}
		Chrome.bot.nazi.redispatch(create(KeyEvent.KEY_PRESSED, keystroke.getModifiers(), keycode, c, KeyEvent.KEY_LOCATION_STANDARD));
		Chrome.bot.nazi.redispatch(create(KeyEvent.KEY_TYPED, keystroke.getModifiers(), 0, c, KeyEvent.KEY_LOCATION_UNKNOWN));
		Task.sleep(50, 75);
		Chrome.bot.nazi.redispatch(create(KeyEvent.KEY_RELEASED, keystroke.getModifiers(), keycode, c, KeyEvent.KEY_LOCATION_STANDARD));
	}

	/**
	 * Presses the key of the given parameter, then presses enter.
	 *
	 * @param c The character to press.
	 */
	public static void sendKey(final char c) {
		pressKey(c);
		pressEnter();
	}

	/**
	 * Presses the keys of the given parameter.
	 *
	 * @param chars The characters to press.
	 */
	public static void pressKeys(final char[] chars) {
		for (final char c : chars) {
			pressKey(c);
		}
	}

	/**
	 * Presses the keys of the given parameter, then presses enter.
	 *
	 * @param chars The characters to press.
	 */
	public static void sendKeys(final char[] chars) {
		pressKeys(chars);
		pressEnter();
	}

	/**
	 * Types the string of the given parameter.
	 *
	 * @param string The string to type.
	 */
	public static void typeString(final String string) {
		pressKeys(string.toCharArray());
	}

	/**
	 * Types the string of the given parameter, then presses enter.
	 *
	 * @param string The string to type.
	 */
	public static void sendString(final String string) {
		typeString(string);
		pressEnter();
	}
}